<template>
  <a-card>
    <!-- 查询   -->
    <a-form
        ref="searchFormRef"
        :model="search_form"
        @submit="handleSearchSubmit"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left">
      <a-row>
        <a-col :flex="1">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="部门名称" field="departmentName">
                <a-input placeholder="请输入部门名称" v-model="search_form.departmentName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="部门描述" field="departmentDesc">
                <a-input placeholder="请输入部门描述" v-model="search_form.departmentDesc"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
        </a-col>
        <a-divider style="height: 84px" direction="vertical"/>
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" html-type="submit">
              <template #icon>
                <icon-search/>
              </template>
              查询
            </a-button>
            <a-button @click="$refs.searchFormRef.resetFields()">
              <template #icon>
                <icon-refresh/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <a-divider/>
      <!-- 添加操作   -->
      <a-row>
        <a-col :span="6" style="padding-bottom: 10px">
          <a-space>
            <a-button
                type="primary" shape="round" @click="addDepartmentOpen">
              <template #icon>
                <icon-plus/>
              </template>
              <template #default>新增部门</template>
            </a-button>
            <a-button shape="round">
              导出表格
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="12" class="mb-1"></a-col>
      </a-row>
    </a-form>
    <!-- 信息展示   -->
    <a-table :columns="columns" :data="departments"
             :pagination="pagination"
             @page-change="handlePaginationChange" style="height: 70vh">
      <template #operations="{record,rowIndex}">
        <a-space>
          <a-button
              type="outline" @click="editDepartmentOpen(record)">
            <template #icon>
              <icon-edit/>
            </template>
            编辑
          </a-button>
          <a-button
              type="outline" status="danger" @click="deleteDepartmentFun(record.departmentIdWbxqy)">
            <template #icon>
              <icon-delete/>
            </template>
            删除
          </a-button>
        </a-space>
      </template>
    </a-table>
    <!-- 添加部门对话框   -->
    <a-modal v-model:visible="showAddDepartmentModal" title="添加部门" @before-ok="addDepartmentOk"
             @cancel="addDepartmentCancel">
      <a-form ref="addDepartmentFormRef" :model="addDepartmentForm" :rules="rules">
        <a-form-item label="部门名称" field="departmentNameWbxqy">
          <a-input v-model="addDepartmentForm.departmentNameWbxqy"/>
        </a-form-item>
        <a-form-item label="部门描述" field="departmentDescWbxqy">
          <a-input v-model="addDepartmentForm.departmentDescWbxqy"/>
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 编辑部门对话框   -->
    <a-modal v-model:visible="showEditDepartmentModal" title="编辑部门" @before-ok="editDepartmentOk"
             @cancel="editDepartmentCancel">
      <a-form ref="editDepartmentFormRef" :model="editDepartmentForm" :rules="rules">
        <a-form-item label="部门名称" field="departmentNameWbxqy">
          <a-input v-model="editDepartmentForm.departmentNameWbxqy"/>
        </a-form-item>
        <a-form-item label="部门描述" field="departmentDescWbxqy">
          <a-input v-model="editDepartmentForm.departmentDescWbxqy"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {addDepartment, getAllDepartments, deleteDepartment, updateDepartment} from '@/api/departmentMG';
import {Message} from "@arco-design/web-vue";
import {IconEdit, IconPlus,IconSearch,IconRefresh,IconDelete} from '@arco-design/web-vue/es/icon';

const departments = ref([]);
const pagination = ref({
  current: 1,   // 当前页数
  pageSize: 10, // 每页条数
  total: 0      // 数据总数
});
const columns = [
  {title: 'ID', dataIndex: 'departmentIdWbxqy'},
  {title: '部门名称', dataIndex: 'departmentNameWbxqy'},
  {title: '部门描述', dataIndex: 'departmentDescWbxqy'},
  {
    title: '操作',
    dataIndex: 'operation',
    width: '150',
    align: 'center',
    slotName: 'operations',
    fixed: 'right'
  }
];
// 添加部门
const addDepartmentFormRef = ref(null)
const showAddDepartmentModal = ref(false);
const addDepartmentForm = reactive({
  departmentNameWbxqy: '',
  departmentDescWbxqy: ''
});
const rules = {
  departmentNameWbxqy: [
    {required: true, message: '部门名称不能为空', trigger: 'blur'},
  ],
  departmentDescWbxqy: [
    {required: true, message: '部门描述不能为空', trigger: 'blur'},
  ]
};
const addDepartmentOpen = async () => {
  showAddDepartmentModal.value = true
}
const addDepartmentOk = async (done) => {
  //进行表单校验
  const res = await addDepartmentFormRef.value.validate();
  if (res) {
    done(false);
    return;
  }
  // 清除值为空的属性
  for (const key in addDepartmentForm) {
    if (addDepartmentForm[key] === '') {
      delete addDepartmentForm[key];
    }
  }
  await addDepartment(addDepartmentForm).then(res => {
    done()
    Message.success({
      content: "添加部门成功",
      duration: "3000"
    })
    // 清空数据
    addDepartmentFormRef.value.resetFields()
    // 重新查询
    fetchData()
  }).catch(err => {
    console.log("添加部门失败", err)
  })
}
const addDepartmentCancel = () => {
  addDepartmentFormRef.value.resetFields()
  showAddDepartmentModal.value = false;
}
// 删除部门
const deleteDepartmentFun = async (departmentId) => {
  await deleteDepartment(departmentId).then(res => {
    Message.success({
      content: "删除部门成功",
      duration: "3000"
    })
    // 重新查询
    fetchData()
  }).catch(err => {
    console.log("删除部门失败", err)
  })
}
// 编辑部门
const editDepartmentFormRef = ref(null)
const showEditDepartmentModal = ref(false);
const editDepartmentForm = reactive({
  departmentIdWbxqy: '',
  departmentNameWbxqy: '',
  departmentDescWbxqy: ''
});
const editDepartmentOpen = async (department) => {
  editDepartmentForm.departmentIdWbxqy = department.departmentIdWbxqy
  editDepartmentForm.departmentNameWbxqy = department.departmentNameWbxqy
  editDepartmentForm.departmentDescWbxqy = department.departmentDescWbxqy
  showEditDepartmentModal.value = true
}
const editDepartmentOk = async (done) => {
  //进行表单校验
  const res = await editDepartmentFormRef.value.validate();
  if (res) {
    done(false);
    return;
  }
  // 清除值为空的属性
  for (const key in editDepartmentForm) {
    if (editDepartmentForm[key] === '') {
      delete editDepartmentForm[key];
    }
  }
  await updateDepartment(editDepartmentForm).then(res => {
    done()
    Message.success({
      content: "编辑部门成功",
      duration: "3000"
    })
    // 清空数据
    editDepartmentFormRef.value.resetFields()
    // 重新查询
    fetchData()
  }).catch(err => {
    console.log("编辑部门失败", err)
  })
}
const editDepartmentCancel = () => {
  editDepartmentFormRef.value.resetFields()
  showEditDepartmentModal.value = false;
}
// 获取所有部门
const search_form = reactive({
  departmentName: '',
  departmentDesc: ''
})
const handleSearchSubmit = (params) => {
  pagination.value.current = 1;
  fetchData();
}

const fetchData = async () => {
  const {current, pageSize} = pagination.value;
  const params = {
    page: current,
    pageSize,
    ...search_form,
  }
  await getAllDepartments(params).then(res => {
    departments.value = res.records
    pagination.value.total = res.total
  }).catch(err => {
    console.log("获取部门列表失败", err)
  })
}
const handlePaginationChange = (page) => {
  pagination.value.current = page
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>
